/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { typeOf } from '../../../utils/is.js';
/**
 * Improve error messages for statistics functions. Errors are typically
 * thrown in an internally used function like larger, causing the error
 * not to mention the function (like max) which is actually used by the user.
 *
 * @param {Error} err
 * @param {String} fnName
 * @param {*} [value]
 * @return {Error}
 */

export function improveErrorMessage(err, fnName, value) {
  // TODO: add information with the index (also needs transform in expression parser)
  var details;

  if (String(err).indexOf('Unexpected type') !== -1) {
    details = arguments.length > 2 ? ' (type: ' + typeOf(value) + ', value: ' + JSON.stringify(value) + ')' : ' (type: ' + err.data.actual + ')';
    return new TypeError('Cannot calculate ' + fnName + ', unexpected type of argument' + details);
  }

  if (String(err).indexOf('complex numbers') !== -1) {
    details = arguments.length > 2 ? ' (type: ' + typeOf(value) + ', value: ' + JSON.stringify(value) + ')' : '';
    return new TypeError('Cannot calculate ' + fnName + ', no ordering relation is defined for complex numbers' + details);
  }

  return err;
}